#!/usr/bin/perl
#
# Take a place name as an argument, and display
# interesting information about its users.
#
use Counter;
use POSIX;
use FillForm;
use Counter::CGI;
use CGI::Carp;
use CounterCGI;
use ErrorForm;

require "temp/countrydata.pl";

$] > 5.008 && binmode(STDOUT, ":utf8"); # set web page output to utf-8
# this shoud retrieve all query information
$q = new Counter::CGI;
$recname = $q->param("place");
if (!$recname) { # older style
    @names = $q->keywords();
    $recname = join(" ", @names);
}
$orderby = $q->param("orderby");
$file = FileTable::open("db/places", O_RONLY);
$persons = FileTable::open("db/persons", O_RONLY);
$users = FileTable::open("db/users", O_RONLY);
$rec = $file->getbykey(name, $recname);
$within = $file->get($rec->{within}) if $rec->{within};
if (!$rec) {
    errorForm("no such place as $recname");
}
$offset = $q->param("offset") + 0;

if ($orderby) { 
    warn "Ordering by $orderby\n";
    @userlist = $persons->select("placeid = ?  ORDER BY $orderby LIMIT ?, 100",
				 $recname, $offset);
} else {
    @userlist = $persons->select("placeid = ? LIMIT ?, 100",
				 $recname, $offset);
}
warn "select found ", @userlist + 0, " users\n";
$usercount = $persons->count("placeid = ?", $recname);

if ($offset > 0) {
    $prevoffset = $offset - 100;
    $prevoffset = 0 if $prevoffset < 0;
}
if (@userlist >= 100) {
    $nextoffset = $offset + 100;
}
if ($offset || $nextoffset) {
    if ($nextoffset) {
	$display = ($offset + 1) . " to $nextoffset ";
    } else {
	$display = ($offset + 1) . " to " . (@userlist + $offset) . " ";
    }
}
#
# Show the user list
#
print <<EoF;
Content-type: text/html; charset="utf-8"

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.or
g/TR/html4/loose.dtd">

<html>
EoF
CounterCGI::pagehead(__("User information for") . " " . "$$rec{name}");
print "<body bgcolor=white>\n";
CounterCGI::pagetop($q);
print "<h1><img src=\"/gifs/Logo-small.png\" alt=\"" . __("Linux Counter Logo") . "\">";
print __("Users") .  " ${display}" . __("listed in") . " $recname</h1>";
print __("Note: This is only from the") . " $usercount " . __("directly listed users. If this place has subordinate places, there may be people listed there.");
print "<p>";
if ($orderby) {
    print __("The list is sorted by") . " $orderby<p>\n";
}

pagelist();

print <<EoF;
<table border>
<tr>
EoF
    print "<th>" . __("Key") . "</th>\n";
   print "<th><a href=\"", userlisturl(undef, undef, "name"), "\">", __("Name"), "</a></th>\n";
   print "<th>", __("Real Email"), "<br><a href=\"", userlisturl(undef, undef, "email"),
    "\">", __("Public Email"), "</a></th>\n";
   print "<th><a href=\"", userlisturl(undef, undef, "city"), "\">", __("City"), "</a></th>\n";
   print "<th><a href=\"", userlisturl(undef, undef, "state"), "\">", __("State/province/department"), "</a></th>\n";
   print "<th><a href=\"", userlisturl(undef, undef, "country"), "\">", __("Country"), "</a></th></tr>\n";
print "\n";
for $user (@userlist) {
	$userkey = $user->key;
	push(@keylist, $userkey);
	$cleanuser = $persons->getclean($userkey);
	$userrec = $users->get($userkey);
        if ($userrec->{state} eq "bad") {
	    $color = " bgcolor=\"red\"";
        } else {
	    $color = "";
        }
	print "<tr><td$color><a href=\"/cgi-bin/adm/display-person.cgi?user=$userkey\">$userkey</a></td>\n";

    for $field (qw(name email city state country)) {
	if ($field eq "email") {
	    print "<td>";
            my $my_email = $userrec->{email};
            $my_email =~ s/@/&#x40;/g;
            print $my_email, "<br>";
            # Replaced next line with previous three
            # print $userrec->{email}, "<br>";
	    if ($user->{email}) {
                my $my_email = $user->{email};
                $my_email =~ s/@/&#x40;/g;
                print $my_email if $user->{email} ne $userrec->{email};
		print "</td>\n";
                # Replaced next line with previous three
                # print $user->{email} if $user->{email} ne $userrec->{email};
	    } else {
		print "<i>", __("empty"), "</i>";
	    }
	} else {
	    print "<td>", $user->{$field};
	}
	if ($cleanuser) {
	    if (!$cleanuser->{$field} && $user->{$field}) {
		print "<br><i>", __("ignored"), "</i>";
	    } elsif ($cleanuser->{$field} ne $user->{$field}) {
		print "<br><i>", $cleanuser->{$field}, "</i>";
	    }
	} else {
	    print "<br>", __("Clean record missing");
	}
    }
    print "</td>\n</tr>\n";
}
print "</table>\n";

if ($q->remote_user) {
    print __("You are user"), " " , $q->remote_user, " ", __("authenticated by"), " ",
    $q->auth_type, "<p>\n";

$users = join(" ", @keylist);
$url = $q->self_url;

pagelist();

print <<EoF;
<form method="POST" action="reclean.cgi">
<input type=hidden name="keys" value="$users">
<input type=hidden name="back" value="$url">
EoF
print "<input type=submit value=\"", __("Clean records"), "\">";
print <<EoF;
</form>
<form method="POST" action="moverecords.cgi">
<input type=hidden name="place" value="$$rec{name}">
EoF
print "<input type=submit value=\"", __("Move records"), "\">";
print <<EoF;
</form>
EoF
}

print <<EoF;
<hr>
EoF
print __("Contact"), ": <a href=\"mailto:webmaster&#x40;counter.li.org\">Webmaster&#x40;counter.li.org</a>";
print <<EoF;
<br>
</body>
</html>
EoF

sub urlname {
# return a string containing an URL to show a place
    my $rec = shift;
    my $str;
    my $name = $rec->{name};
    $name =~ s/ /+/g;
    $name =~ s/\,/%2C/g;
    $str = sprintf("<a href=\"/cgi-bin/runscript/place.cgi?%s\">%s</a>",
		   $name, $rec->{longname});
}


sub pagelist {
# List other pages of userrecs for this place

    return if $usercount < 100;
    print __("User no."), " ";
    for ($offsetx = 0; $offsetx < $usercount; $offsetx += 100) {
	if ($offsetx == $offset) {
	    print $offsetx?$offsetx:__("First"), " ";
	} else {
	    my $name = $recname;
	    $name =~ s/ /+/g;
	    $name =~ s/\,/%2C/g;
	    print "<a href=\"", userlisturl($name, $offsetx), "\">",
	        $offsetx?$offsetx:__("First"), "</a> \n";
	}
    }
    print "<p>\n";
}    

sub userlisturl {
    my ($namex, $offsetx, $orderbyx) = @_;
 
    # Pull in defaults from globals
    $namex = $recname if !defined($namex);
    $offsetx = $offset if !defined($offsetx);
    $orderbyx = $orderby if !defined($orderbyx);
    $namex = urlquote($namex);
    return "userlist.cgi?place=$namex&offset=$offsetx&orderby=$orderbyx";
}
